package com.jqr.school.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jqr.school.po.Article;
import com.jqr.school.po.ArticleCat;
import com.jqr.school.service.ArticleCatService;
import com.jqr.school.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuzongbo
 * @since 2022-01-18
 */
@Controller
@RequestMapping("/admin/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private ArticleCatService articleCatService;
    @RequestMapping("/index")
    public  String index(Model model){
        QueryWrapper<Article> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("id","cat_id","title");
        Page<Article> page=new Page<>(1,20);
        articleService.page(page,queryWrapper);
        model.addAttribute("page",page);
        return  "admin/article/index";

    }
    @GetMapping("/toedit")
    public  String toeidt(Model model,Integer id){
        Article article=null;
        if(id!=null){
         article=   articleService.getById(id);
         model.addAttribute("article",article);
        }
        else {
            article=new Article();
        }

        List<ArticleCat> articleCatList=articleCatService.list();
        model.addAttribute("article",article);
        model.addAttribute("articleCatList",articleCatList);
        return  "admin/article/edit";
    }
   @PostMapping("/edit")
    public String edit(@Validated Article article, BindingResult result){
        if(result.hasErrors()){
            return  "admin/article/edit";

        }
        if(article.getId()!=null){
            articleService.updateById(article);
        }
        else{
            articleService.save(article);
        }
        return "redirect:index";
    }
    @GetMapping("/delete")
    public  String delete(@NotNull Integer id){
        if(id!=null){
            articleService.removeById(id);
        }
        return "redirect:index";
    }
}
